package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
)

func main() {
	http.HandleFunc("/", handler)
	http.HandleFunc("/healthz", healthz)
	http.ListenAndServe(":80", nil)
}

func healthz(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
	w.Write([]byte("OK"))
}

func handler(w http.ResponseWriter, r *http.Request) {
	for i, _ := range r.Header {
		w.Header().Set(i, r.Header.Get(i))
	}
	version := os.Getenv("VERSION")
	w.Header().Set("VERSION", version)
	ip, _ := remoteIp(r)
	fmt.Println(ip)
}

func remoteIp(req *http.Request) (string, error) {
	ip, _, err := net.SplitHostPort(req.RemoteAddr)
	if err != nil {
		log.Fatalf("Getting req.RemoteAddr %v", err)
		return "", err
	}
	userIP := net.ParseIP(ip)

	return userIP.String(), nil
}
